package com.greendeliver.activities;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.example.test.R;
import com.greendeliver.business.ServiceManager;

public class AllStoresActivity extends ListActivity {

	private ArrayList<HashMap<String, String>>	servicesList;

	private ProgressDialog						pDialog;

	private static final String					TAG_ID		= "ID_service";
	private static final String					TAG_NAME	= "name_service";

	@Override
	protected void onCreate( Bundle savedInstanceState ) {
		super.onCreate( savedInstanceState );
		setContentView( R.layout.activity_all_stores );

		this.pDialog = new ProgressDialog( AllStoresActivity.this );
		servicesList = new ArrayList<HashMap<String, String>>();

		new Load().execute();

		ListView lv = getListView();

		// on seleting single product
		// launching Edit Product Screen
		lv.setOnItemClickListener( new OnItemClickListener() {

			@Override
			public void onItemClick( AdapterView<?> parent, View view,
					int position, long id ) {
				// getting values from selected ListItem
				String id_service = ( (TextView) view.findViewById( R.id.id_service ) ).getText().toString();

				// Starting new intent
				Intent in = new Intent( getApplicationContext(), ServiceDetailActivity.class );
				// sending id to next activity
				in.putExtra( TAG_ID, id_service );

				// starting new activity and expecting some response back
				startActivity( in );
			}
		} );
	}

	class Load extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute()
		{
			super.onPreExecute();
			pDialog.setMessage( "Chargement des Boutiques" );
			pDialog.setIndeterminate( false );
			pDialog.setCancelable( false );
			pDialog.show();
		}

		/**
		 * getting All products from url
		 * */
		@Override
		protected String doInBackground( String... args )
		{
			ServiceManager sm = new ServiceManager();
			servicesList = sm.get_all_stores();

			return null;
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		@Override
		protected void onPostExecute( String file_url )
		{
			pDialog.dismiss();

			ListAdapter adapter = new SimpleAdapter( AllStoresActivity.this,
					servicesList, R.layout.list_item_service,
					new String[] { TAG_ID, TAG_NAME },
					new int[] { R.id.id_service, R.id.name_service, } );
			setListAdapter( adapter );
		}
	}

}
